#!/usr/bin/python
# -*- coding: UTF-8 -*-
# @License: Copyright © 2019 代鹏. All rights reserved.
# @Author: 代鹏
# @Contact: 272481080@qq.com
# @File: mongo.py
# @Date: 2019/6/18
# @Software：kk
# @description :
# -*- coding: utf-8 -*-
from app.server.cu_mongodb import MongoConn
import traceback


def check_connected(conn):
    # 检查是否连接成功
    if not conn.connected:
        raise NameError('stat:connected Error')
    # print('connecte ok')

def save(table, value):
    # 一次操作一条记录，根据‘_id’是否存在，决定插入或更新记录
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        my_conn.db[table].save(value)
    except Exception:
        print(traceback.format_exc())


def insert_many(table, value):
    # 可以使用insert直接一次性向mongoDB插入整个列表，也可以插入单条记录，但是'_id'重复会报错
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        my_conn.db[table].insert_many(value, continue_on_error=True)
    except Exception:
        print(traceback.format_exc())


def update_one(table, conditions, value, s_upsert=False, s_multi=False):
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        my_conn.db[table].update_one(conditions, value, upsert=s_upsert, multi=s_multi)
    except Exception:
        print(traceback.format_exc())


def upsert_mary(table, datas):
    # 批量更新插入，根据‘_id’更新或插入多条记录。
    # 把'_id'值不存在的记录，插入数据库。'_id'值存在，则更新记录。
    # 如果更新的字段在mongo中不存在，则直接新增一个字段
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        bulk = my_conn.db[table].initialize_ordered_bulk_op()
        for data in datas:
            _id = data['_id']
            bulk.find({'_id': _id}).upsert().update({'$set': data})
        bulk.execute()
    except Exception:
        print(traceback.format_exc())


def upsert_one(table, data):
    # 更新插入，根据‘_id’更新一条记录，如果‘_id’的值不存在，则插入一条记录
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        query = {'_id': data.get('_id', '')}
        if not my_conn.db[table].find_one(query):
            my_conn.db[table].insert(data)
        else:
            data.pop('_id')  # 删除'_id'键
            my_conn.db[table].update(query, {'$set': data})
    except Exception:
        print(traceback.format_exc())


def find_one(table, value):
    # 根据条件进行查询，返回一条记录
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        return my_conn.db[table].find_one(value)
    except Exception:
        print(traceback.format_exc())


def find(table, value):
    # 根据条件进行查询，返回所有记录
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        return my_conn.db[table].find(value)
    except Exception:
        print(traceback.format_exc())


def select_colum(table, value, colum):
    # 查询指定列的所有值
    try:
        my_conn = MongoConn()
        check_connected(my_conn)
        return my_conn.db[table].find(value, {colum: 1})
    except Exception:
        print(traceback.format_exc())

def save_wiki():
    file_path = './readme.md'
    f = open(file_path, "r")
    dic = {}
    dic['_id'] = '12345678'
    dic['content'] = f.read()
    save('wiki_content', dic)
def find_wiki():
    res = find_one('wiki_content', {})
    for k in res:
        print(k, ':', res[k])
def test():
    file_path = './enterprise_all.txt'
    company_list = []
    with open(file_path, "r") as in_file:
        for line in in_file:
            dic = {}
            dic['_id'] = line.strip()
            dic['name'] = line.strip()
            company_list.append(dic)
    upsert_mary('mytest', company_list)

    datas = [
        {'_id': 8, 'data': 88},
        {'_id': 9, 'data': 99},
        {'_id': 36, 'data': 3366}
    ]

    # 插入,'_id' 的值必须不存在，否则报错
    insert_many('mytest', datas)
    # 插入
    data = {'_id': 6, 'data': 66}
    save('mytest', data)
    # 更新数据
    update_one('mytest', {'_id': 8}, {'$set': {'data': '888'}}, False, False)
    # 更新或插入
    data = {'_id': 36, 'data': 'dsd'}
    upsert_one('mytest', data)
    # 查找。相对于 select _id from mytest
    res = select_colum('mytest', {}, '_id')
    for k in res:
        for key, value in k.items():
            print(key, ":", value)
    # 查找。相对于 select * from mytest
    res = find('mytest', {})
    for k in res:
        for key, value in k.items():
            print(key, ":", value)
        print()
    # 查找。相对于 select * from mytest limit 1
    res = find_one('mytest', {})
    for k in res:
        print(k, ':', res[k])


if __name__ == "__main__":
    # test()
    # save_wiki()
    find_wiki()
